package com.gaotu.demo.transaction.daosupport;

import com.gaotu.demo.transaction.User;
import com.gaotu.demo.transaction.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Date;
import java.util.Random;

@Service
public class UserService {
    @Autowired
    private JdbcBasedDaoSupportUserRepository jdbcBasedDaoSupportUserRepository;
    @Autowired
    private JpaBasedDaoSupportUserRepository jpaBasedDaoSupportUserRepository;
    @Autowired
    private MybatisBasedDaoSupportUserRepository mybatisBasedDaoSupportUserRepository;

    @Autowired
    private TransactionTemplate dataSourceTransactionTemplate;

    @Autowired
    private TransactionTemplate jpaTransactionTemplate;

    @Autowired
    private TransactionTemplate sqlSessionTransactionTemplate;


    @Transactional(transactionManager = "dataSourceTransactionManager", readOnly = false)
    public User jdbcWithAnnotation(){
        return doWithRepository(jdbcBasedDaoSupportUserRepository);
    }

    @Transactional(transactionManager = "jpaTransactionManager", readOnly = false)
    public User jpaWithAnnotation(){
        return doWithRepository(jpaBasedDaoSupportUserRepository);
    }

    @Transactional(transactionManager = "sqlSessionTransactionManager", readOnly = false)
    public User mybatisWithAnnotation(){
        return doWithRepository(mybatisBasedDaoSupportUserRepository);
    }


    public User jdbcWithTemplate(){
        return this.dataSourceTransactionTemplate.execute(status ->  doWithRepository(jdbcBasedDaoSupportUserRepository));
    }


    public User jpaWithTemplate(){
        return this.jpaTransactionTemplate.execute(status ->  doWithRepository(jpaBasedDaoSupportUserRepository));
    }


    public User mybatisWithTemplate(){
        return this.sqlSessionTransactionTemplate.execute(status ->  doWithRepository(mybatisBasedDaoSupportUserRepository));
    }

    private User doWithRepository(UserRepository userRepository){
        Random random = new Random();
        String userName = String.valueOf(random.nextInt());
        {

            User user = User.builder()
                    .userName(userName)
                    .pwd(String.valueOf(random.nextInt()))
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();
            userRepository.save(user);
        }
        {
            User user = userRepository.getByUserName(userName);
            return user;

        }
    }
}
